package com.hystrix.collapser;

import com.hystrix.command.CollapsedCommand;
import com.hystrix.entity.Person;
import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCommand;

import java.util.Collection;
import java.util.Map;

/**
 * 合并处理器
 * 第一个类型为批处理返回的结果类型
 * 第二个为单请求返回的结果类型
 * 第三个是请求参数类型
 * Created by earl on 2018/5/2.
 */
public class MyHystrixCollapser extends HystrixCollapser <Map<String,Person>,Person,String> {

    String personName;

    public MyHystrixCollapser(String personName){
        this.personName = personName;
    }

    @Override
    public String getRequestArgument() {
        return personName;
    }

    @Override
    protected HystrixCommand<Map<String, Person>> createCommand(Collection<CollapsedRequest<Person, String>> requests) {
        return new CollapsedCommand(requests);
    }

    @Override
    protected void mapResponseToRequests(Map<String, Person> stringPersonMap, Collection<CollapsedRequest<Person, String>> requests) {
        //让结果和请求关联起来
        requests.forEach(request->{
            //获取单个响应返回的结果
            Person p = stringPersonMap.get(request.getArgument());
            //关联到请求中
            request.setResponse(p);
        });
    }
}
